package com.tianhui.consignortwofei.mvp.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.fgs.common.CommonFragment;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.adapter.FragmentPagerAdapter;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.widget.CustomViewPager;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseFragment;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.model.UserInfoModel;
import com.tianhui.consignortwofei.mvp.model.enty.ConsignorInfo;
import com.tianhui.consignortwofei.mvp.model.enty.UserInfo;
import com.tianhui.consignortwofei.mvp.ui.activity.ConsignorListActivity;
import com.tianhui.consignortwofei.other.EventWhat;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.BoToExamineStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.DaFuDispatchStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.FreightStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.QuXiaoDispatchStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.SaleCarFreightStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.SourceStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.WanChengDispatchStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.WanChengXiaoStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.WeiToExamineStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.YiQiangDispatchStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.YiSaleCarFreightStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.YiToExamineStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.YunShuDispatchStatus;
import com.tianhui.consignortwofei.role.RoleController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * @author fgs
 * @date 2020/9/9
 * @description
 **/
public class WaybillFragment extends BaseFragment {

    @BindView(R.id.activity_order_list_viewPager)
    CustomViewPager mViewPager;
    @BindView(R.id.activity_order_list_slidingTabLayout)
    SlidingTabLayout mTabLayout;
    @BindView(R.id.activity_order_list_TabFrameLayout)
    FrameLayout mTabFrameLayout;


    @BindView(R.id.tv_toolbar_title)
    TextView tv_toolbar_title;


    @BindView(R.id.iv_more)
    TextView iv_more;
    @BindView(R.id.tv_all_num)
    TextView tv_all_num;


    private List<CommonFragment> mFragmentList = new ArrayList<>();
    private FragmentPagerAdapter mPagerAdapter;
    private int rolePosition;

    public WaybillFragment() {
        // Required empty public constructor
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_list;
    }

    @Override
    protected CommonView createView() {
        return null;
    }

    @Override
    protected CommonPresenter createPresenter() {
        return null;
    }

    @Override
    protected void init() {

        tv_toolbar_title.setText("运单管理");

        rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
        List<String> tablist;

        if (2 == rolePosition) {
            //2 销售，3物流
            createFragmentListTwo();
            tablist = Arrays.asList(getResources().getStringArray(R.array.array_yuadan_tab_two));
            mTabLayout.setTabSpaceEqual(true);

            iv_more.setVisibility(View.GONE);
            tv_all_num.setVisibility(View.GONE);
        } else {
            createFragmentList();
            tablist = Arrays.asList(getResources().getStringArray(R.array.array_yuadan_tab));
            mTabLayout.setTabSpaceEqual(false);
        }

        mPagerAdapter = new FragmentPagerAdapter(getFragmentManager());
//        mPagerAdapter.setFragments(createFragmentList());
        mPagerAdapter.setFragments(mFragmentList);
        mViewPager.setCanScroll(false);
        mViewPager.setHasEffect(false);
        mViewPager.setOffscreenPageLimit(mFragmentList.size());
        mViewPager.setAdapter(mPagerAdapter);

        mPagerAdapter.setTabTitles(tablist);
        mTabLayout.setViewPager(mViewPager);


//        Bundle bundle = getIntent().getExtras();
        int index = 0;
//        if (bundle != null && !bundle.isEmpty()) {
//            index = bundle.getInt(KeyValue.KEY_TYPE);
//            if (index == OrderType.TYPE_SOURCE) {
//        if (2 == rolePosition) {
//            //2 销售，3物流
//            setCurrentItem(3);
//        } else {
            setCurrentItem(0);
//        }

//                getToolbarStatus().setTitle("货源管理");
//            }
////            else if (index == OrderType.TYPE_INQUIRY) {
////                setCurrentItem(1);
////                getToolbarStatus().setTitle("询价管理");
////            }
//            else if (index == OrderType.TYPE_DISPATCH) {
//                setCurrentItem(1);
//        getToolbarStatus().setTitle("调度管理");
//            }
//        }







//        boolean isShowOrderTypeTabLayout = RoleController.getInstance().isShowOrderTypeTabLayout();
//        if (isShowOrderTypeTabLayout) {
            mTabFrameLayout.setVisibility(View.VISIBLE);
//        } else {
//            mTabFrameLayout.setVisibility(View.GONE);
//        }


//        initListener();
    }



    private void initListener() {

        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                switch (position) {
                    case 0:
                        mViewPager.setCurrentItem(0);
//                        getToolbarStatus().setTitle("货源管理");

                        break;
//                    case 1:
//                        mViewPager.setCurrentItem(1);
//                        getToolbarStatus().setTitle("询价管理");
//                        break;
                    case 1:
                        mViewPager.setCurrentItem(1);
//                        getToolbarStatus().setTitle("调度管理");
                        break;
                    case 2:
                        mViewPager.setCurrentItem(2);
//                        getToolbarStatus().setTitle("调度管理");
                        break;
                    case 3:
                        mViewPager.setCurrentItem(3);
//                        getToolbarStatus().setTitle("调度管理");
                        break;
                    case 4:
                        mViewPager.setCurrentItem(4);
//                        getToolbarStatus().setTitle("调度管理");
                        break;
                    case 5:
                        mViewPager.setCurrentItem(5);
//                        getToolbarStatus().setTitle("调度管理");
                        break;
                    case 6:
                        mViewPager.setCurrentItem(6);
//                        getToolbarStatus().setTitle("调度管理");
                        break;


                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

    }

    private List<CommonFragment> createFragmentList() {
//        mFragmentList.add(OrderListFragment.newInstance(new SourceStatus()));//货源
//        mFragmentList.add(OrderListFragment.newInstance(new InquirySourceStatus()));

//          <item>未审核</item><item>已审核</item><item>已拒绝</item>

        mFragmentList.add(new ZhaoCeBillFragment());//找车单
//        mFragmentList.add(ToExamineListFragment.newInstance(new ToExamineStatus()));//总审核单找车单

//        mFragmentList.add(ToExamineListFragment.newInstance(new WeiToExamineStatus(),4));//待审核审核单找车单
//        mFragmentList.add(ToExamineListFragment.newInstance(new YiToExamineStatus(),5));//已审核审核单找车单
//        mFragmentList.add(ToExamineListFragment.newInstance(new DaiQueRenExamineStatus(),7));//待确认
//        mFragmentList.add(ToExamineListFragment.newInstance(new QueRenExamineStatus(),8));//已确认
//        mFragmentList.add(ToExamineListFragment.newInstance(new BoToExamineStatus(),6));//拒绝审核单找车单
//        mFragmentList.add(YanChangListFragment.newInstance(new YanChangExamineStatus(),99));//延长单

//1:未抢单,2:已取消,3:待装货,4:取消确认中,5:确认装车,6:确认收货,7:运输中,9:待收款,10:作废,11:终止,12:已计算,13付款中,14:已完成
//1,3,7,9,14,4
//        mFragmentList.add(OrderListFragment.newInstance(new SourceStatus()));//货源
        mFragmentList.add(SourceDocumentListFragment.newInstance(new SourceStatus()));//货源

        mFragmentList.add(new WaiBuBillFragment());//总外部单
//        mFragmentList.add(ExternalListFragment.newInstance(new ExternalStatus()));//外部单
//        mFragmentList.add(AlreadyWaiListFragment.newInstance(new AlreadyWaiDispatchStatus()));//已确认外部单

//        mFragmentList.add(DispatchListFragment.newInstance(new YiQiangDispatchStatus()));//已抢单
        mFragmentList.add(InTransitListFragment.newInstance(new YiQiangDispatchStatus()));//已抢单
//        mFragmentList.add(DispatchListFragment.newInstance(new YunShuDispatchStatus()));//运输中
        mFragmentList.add(InTransitListFragment.newInstance(new YunShuDispatchStatus()));//运输中
//        mFragmentList.add(DispatchListFragment.newInstance(new DaFuDispatchStatus()));//待收款
        mFragmentList.add(InTransitListFragment.newInstance(new DaFuDispatchStatus()));//待收款



//        mFragmentList.add(OrderListFragment.newInstance(new SourceStatusDingJin()));//有定金
//        mFragmentList.add(OrderListFragment.newInstance(new DispatchStatus()));//调度
//        mFragmentList.add(OrderListFragment.newInstance(new DispatchStatusDingJin()));//有定金

//        mFragmentList.add(OrderListFragment.newInstance(new FreightStatus()).setIsNeedLazyLoad(false).setSearchKey(""));//运费计算
        mFragmentList.add(FreightPayListFragment.newInstance(new FreightStatus()).setIsNeedLazyLoad(false).setSearchKey(""));//运费计算
////        mFragmentList.add(OrderListFragment.newInstance(new PaymentStatus()).setIsNeedLazyLoad(false).setSearchKey(""));//付款申请
//        mFragmentList.add(FreightPayListFragment.newInstance(new PaymentStatus()).setIsNeedLazyLoad(false).setSearchKey(""));//付款申请


//        mFragmentList.add(DispatchListFragment.newInstance(new WanChengDispatchStatus()));//已完成
        mFragmentList.add(InTransitListFragment.newInstance(new WanChengDispatchStatus()));//已完成
//        mFragmentList.add(DispatchListFragment.newInstance(new QuXiaoDispatchStatus()));//取消中
        mFragmentList.add(InTransitListFragment.newInstance(new QuXiaoDispatchStatus()));//取消中

        return mFragmentList;
    }

    private List<CommonFragment> createFragmentListTwo() {

//        mFragmentList.add(ToExamineListFragment.newInstance(new ToExamineStatus()));//审核单
        mFragmentList.add(ToExamineListFragment.newInstance(new WeiToExamineStatus(),1));//待审核审核单找车单
        mFragmentList.add(ToExamineListFragment.newInstance(new YiToExamineStatus(),2));//已审核审核单找车单
        mFragmentList.add(ToExamineListFragment.newInstance(new BoToExamineStatus(),3));//拒绝审核单找车单

//1:未抢单,2:已取消,3:待装货,4:取消确认中,5:确认装车,6:确认收货,7:运输中,9:待收款,10:作废,11:终止,12:已计算,13付款中,14:已完成
//1,3,7,9,14,4
//        mFragmentList.add(InTransitListFragment.newInstance(new DaFuDispatchStatus()));//待收款

        mFragmentList.add(XiaoWeiJiSuanListFragment.newInstance(new SaleCarFreightStatus()).setIsNeedLazyLoad(false).setSearchKey("").setWhichShow(0));//运费计算
        mFragmentList.add(WeiFreightPayListFragment.newInstance(new YiSaleCarFreightStatus()).setIsNeedLazyLoad(false).setSearchKey("").setWhichShow(1));//已计算
//        mFragmentList.add(AlreadyPayListFragment.newInstance(new WanChengXiaoStatus()).setIsNeedLazyLoad(false).setSearchKey("").setWhichShow(1));//已支付
        mFragmentList.add(XiaoWeiJiSuanListFragment.newInstance(new WanChengXiaoStatus()).setIsNeedLazyLoad(false).setSearchKey("").setWhichShow(1));//已支付

        return mFragmentList;
    }

    private void setCurrentItem(int item) {
        mViewPager.setCurrentItem(item);
    }



    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_MOVE_TO_JISUAN:
                mTabLayout.setCurrentTab(5);
                break;
            case CHANGE_TAB_FRAGMENT:
                changeTabFragment();
                break;
//            case EVENT_REFRESH_CONSIGNOR_INFO:
//                changeTabFragment();
//                break;
            case EVENT_REFRESH_ORDER_LIST:
                //刷新货权数量
                if (3== rolePosition){
                    //2 销售，3物流
                    String consignorId = SharedPreferenceManager.getInstance().getConsignorId();
                    requestConsignorGroupListInfo(consignorId);
                }
                break;

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        requestUserInfo();
    }



    private int oldRolePosition=0;
    private void changeTabFragment() {
//        if (mPagerAdapter != null) {
//            int rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
//            if (oldRolePosition != rolePosition) {
//                oldRolePosition = rolePosition;
//                mFragmentList.clear();
//                List<String> list;
//                if (2 == rolePosition) {
//                    //2 销售，3物流
//                    list = Arrays.asList(getResources().getStringArray(R.array.array_yuadan_tab_two));
//                    createFragmentListTwo();
//                    mTabLayout.setTabSpaceEqual(true);
//                } else {
//                    list = Arrays.asList(getResources().getStringArray(R.array.array_yuadan_tab));
//                    createFragmentList();
//                    mTabLayout.setTabSpaceEqual(false);
//                }
//                mPagerAdapter.RefreshFragments(mViewPager, mFragmentList, list);
//                mTabLayout.setViewPager(mViewPager);
//
//            }
//        }
    }


    private UserInfoModel  mUserInfoModel;
    private void requestUserInfo() {
        if (null==mUserInfoModel) {
            mUserInfoModel = new UserInfoModel();
        }
        mUserInfoModel.userInfoModel(getContext(), false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<UserInfo>>() {

            @Override
            public void onNext(CommonResponse<UserInfo> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    UserInfo userInfo = commonResponse.getData();
                    if (userInfo != null && userInfo.profile != null) {
//                        userAccount = userInfo.profile.account;
                        RoleController.getInstance().setRole(userInfo.profile);
                        //认证状态
//                        mAuthStatusView.showAuthStatus(userInfo);

                        SharedPreferenceManager.getInstance().setConsignorId(userInfo.profile.id);
                        SharedPreferenceManager.getInstance().setConsignorName(userInfo.profile.name);
                        SharedPreferenceManager.getInstance().setPhone(userInfo.profile.phone);

                        int rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
//                        if (2== rolePosition){
//                            //2 销售，3物流
//                            ll_putong_send.setVisibility(View.GONE);
//                            ll_zhaoche_send.setVisibility(View.VISIBLE);
////                            initChangeFragment(ToExamineListFragment.newInstance(new ToExamineStatus()));
//                        }else {
//                            ll_putong_send.setVisibility(View.VISIBLE);
//                            ll_zhaoche_send.setVisibility(View.GONE);
////                            initChangeFragment(SourceDocumentListFragment.newInstance(new SourceStatus()));
//                        }



                            if (2== rolePosition){
                                //2 销售，3物流
//                                getJiSuanList();
                            }else {
                                requestConsignorGroupListInfo(userInfo.profile.id);
                            }



                    }


                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }



    private ArrayList<ConsignorInfo> mConsignorInfoList;
    //货权选择列表
    private void requestConsignorGroupListInfo(String id) {
        if (TextUtils.isEmpty(id)) return;
        Map<String, String> map = new HashMap<>();
        map.put("userId", id);
        mUserInfoModel.consignorGroupListModel(getContext(), map, false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<ArrayList<ConsignorInfo>>>() {
            @Override
            public void onNext(CommonResponse<ArrayList<ConsignorInfo>> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    mConsignorInfoList = commonResponse.getData();
                    if (mConsignorInfoList != null && mConsignorInfoList.size() > 0) {

                        int trueNum=0;
                        int allNum=0;
                        for (int i=0;i<mConsignorInfoList.size();i++){
                            ConsignorInfo consignorInfo = mConsignorInfoList.get(i);
                            allNum+=consignorInfo.counts;

                            if (consignorInfo.isLogin){
                                iv_more.setText(consignorInfo.customer+"("+consignorInfo.counts+")");
                                trueNum++;
                            }
                        }
                        tv_all_num.setText(allNum+"");
                        if (trueNum>2){
                            iv_more.setText("待审核找车单");
                        }

//                        boolean isShow=false;
//                        String title="以下货权有找车单";
//                        String go="去切换";
//                        String text="";
//                        for (int i=0;i<mConsignorInfoList.size();i++){
//                            ConsignorInfo consignorInfo = mConsignorInfoList.get(i);
//                            if (!"0".equals(consignorInfo.counts)){
//                                text=text+consignorInfo.customername+"("+consignorInfo.counts+"单)\n";
//                                isShow=true;
//                            }
//                        }
//                        if (isShow){
//                            ShowDialog(title,text,go);
//                        }

                    }
                } else {
                    LogUtil.print(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                LogUtil.print(e.message);
            }
        });
    }


    @OnClick(R.id.tv_all_num)
    public void setHuoQuan() {
        if (mConsignorInfoList != null && mConsignorInfoList.size() > 0) {
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList(KeyValue.KEY_CONSIGNOR_LIST, mConsignorInfoList);
            openActivity(ConsignorListActivity.class, bundle);
        }
    }

    @OnClick(R.id.iv_more)
    public void setHuoQuanTwo() {
        if (mConsignorInfoList != null && mConsignorInfoList.size() > 0) {
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList(KeyValue.KEY_CONSIGNOR_LIST, mConsignorInfoList);
            openActivity(ConsignorListActivity.class, bundle);
        }
    }






}
